import React, { useRef, useEffect, Suspense, useState } from 'react';
import { Canvas, useFrame, useLoader } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';
import { TextureLoader } from 'three';
import { useUserStore } from '../../store/userStore';
import * as THREE from 'three';

interface PlanetMeshProps {
  energyRatio: number; // 0-1之间的值，表示绿色能源占比
}

// 预加载纹理，避免每次渲染都重新加载
const textureLoader = new TextureLoader();
const earthTexturePromise = textureLoader.loadAsync('/textures/earth_day.jpg');
const cloudsTexturePromise = textureLoader.loadAsync('/textures/earth_clouds.png');
const nightTexturePromise = textureLoader.loadAsync('/textures/earth_night.jpg');

// 使用更低精度的几何体进行初始渲染
const LOW_DETAIL: [number, number, number] = [1, 16, 16]; // 低精度球体参数
const HIGH_DETAIL: [number, number, number] = [1, 64, 64]; // 高精度球体参数

const PlanetMesh: React.FC<PlanetMeshProps> = ({ energyRatio }) => {
  const planetRef = useRef<THREE.Mesh>(null);
  const cloudsRef = useRef<THREE.Mesh>(null);
  const nightRef = useRef<THREE.Mesh>(null);
  const [detail, setDetail] = useState(LOW_DETAIL);
  const [earthTexture, setEarthTexture] = useState<THREE.Texture | null>(null);
  const [cloudsTexture, setCloudsTexture] = useState<THREE.Texture | null>(null);
  const [nightTexture, setNightTexture] = useState<THREE.Texture | null>(null);
  const [loaded, setLoaded] = useState(false);

  // 加载纹理
  useEffect(() => {
    Promise.all([earthTexturePromise, cloudsTexturePromise, nightTexturePromise])
      .then(([earth, clouds, night]) => {
        setEarthTexture(earth);
        setCloudsTexture(clouds);
        setNightTexture(night);
        setLoaded(true);
        
        // 在纹理加载完成后，延迟增加几何体的细节
        setTimeout(() => setDetail(HIGH_DETAIL), 1000);
      })
      .catch(error => console.error('Failed to load textures:', error));
  }, []);

  // 根据能量比例计算材质属性
  const dayIntensity = Math.max(0.3, energyRatio); // 最小亮度为0.3
  const nightOpacity = Math.max(0, 1 - energyRatio * 0.8); // 夜间亮度相反，能量高时夜间亮度低
  const cloudOpacity = Math.min(0.7, 0.3 + energyRatio * 0.4); // 云层随能量增加而增加透明度，范围0.3-0.7

  // 更新材质属性
  useEffect(() => {
    if (!loaded) return;
    
    if (planetRef.current && planetRef.current.material) {
      (planetRef.current.material as THREE.MeshStandardMaterial).emissiveIntensity = dayIntensity;
    }
    if (nightRef.current && nightRef.current.material) {
      (nightRef.current.material as THREE.MeshStandardMaterial).opacity = nightOpacity;
    }
    if (cloudsRef.current && cloudsRef.current.material) {
      (cloudsRef.current.material as THREE.MeshPhongMaterial).opacity = cloudOpacity;
    }
  }, [dayIntensity, nightOpacity, cloudOpacity, loaded]);

  // 动画效果 - 减少动画复杂度
  useFrame(({ clock }) => {
    if (!loaded) return;
    
    const time = clock.getElapsedTime();
    
    if (cloudsRef.current) {
      cloudsRef.current.rotation.y = time * 0.03; // 降低旋转速度
    }
    if (planetRef.current && nightRef.current) {
      const rotation = time * 0.05; // 降低旋转速度
      planetRef.current.rotation.y = rotation;
      nightRef.current.rotation.y = rotation;
    }
  });

  if (!earthTexture || !cloudsTexture || !nightTexture) {
    return (
      <mesh>
        <sphereGeometry args={LOW_DETAIL} />
        <meshBasicMaterial color="#1a5276" />
      </mesh>
    );
  }

  return (
    <group>
      {/* 主星球 */}
      <mesh ref={planetRef} castShadow receiveShadow>
        <sphereGeometry args={[detail[0], detail[1], detail[2]]} />
        <meshStandardMaterial 
          map={earthTexture} 
          emissive="#ffffff"
          emissiveIntensity={dayIntensity}
        />
      </mesh>

      {/* 云层 */}
      <mesh ref={cloudsRef} scale={1.01}>
        <sphereGeometry args={[detail[0], Math.max(16, Math.floor(detail[1]/2)), Math.max(16, Math.floor(detail[2]/2))]} />
        <meshPhongMaterial
          map={cloudsTexture}
          transparent={true}
          opacity={cloudOpacity}
          depthWrite={false}
          blending={THREE.AdditiveBlending}
        />
      </mesh>

      {/* 夜晚灯光 */}
      <mesh ref={nightRef} scale={1.001}>
        <sphereGeometry args={[detail[0], detail[1], detail[2]]} />
        <meshStandardMaterial 
          map={nightTexture} 
          transparent={true}
          opacity={nightOpacity}
        />
      </mesh>
    </group>
  );
};

const PlanetWithSuspense = ({ energyRatio }: PlanetMeshProps) => (
  <Suspense fallback={
    <div style={{
      width: '100%',
      height: '100%',
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      color: '#1a5276',
      background: '#f0f0f0',
      borderRadius: '8px'
    }}>
      加载星球中...
    </div>
  }>
    <PlanetMesh energyRatio={energyRatio} />
  </Suspense>
);

export const Planet: React.FC = () => {
  const { user } = useUserStore();
  const [loaded, setLoaded] = useState(false);
  
  // 计算绿色能源占比
  const energyRatio = user?.planetState.energy 
    ? user.planetState.energy.clean / user.planetState.energy.total 
    : 0.5; // 默认值

  useEffect(() => {
    const handleSourceMapError = (event: ErrorEvent) => {
      if (event.message.includes('vision_bundle_mjs.js.map')) {
        console.warn('Failed to load source map:', event.message);
        event.preventDefault();
      }
    };

    window.addEventListener('error', handleSourceMapError);
    
    // 标记加载完成
    const timer = setTimeout(() => setLoaded(true), 100);

    return () => {
      window.removeEventListener('error', handleSourceMapError);
      clearTimeout(timer);
    };
  }, []);
  
  return (
    <div style={{ width: '100%', height: 'calc(100vh - 40px)' }}>
      {loaded && (
        <div style={{
          position: 'absolute',
          top: '20px',
          right: '20px',
          background: 'rgba(255, 255, 255, 0.9)',
          padding: '20px',
          borderRadius: '12px',
          boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
        }}>
          <h3 style={{ margin: '0 0 10px 0' }}>星球状态</h3>
          <div>污染度：{((user?.planetState.pollution || 0) * 100).toFixed(1)}%</div>
          <div>生物多样性：{((user?.planetState.biodiversity || 0) * 100).toFixed(1)}%</div>
          <div>树木数量：{user?.planetState.trees || 0}</div>
          <div>水质：{((user?.planetState.waterQuality || 0) * 100).toFixed(1)}%</div>
          <div style={{ marginTop: '10px', fontWeight: 'bold', color: energyRatio >= 0.6 ? '#3f8600' : '#cf1322' }}>
            绿色能源: {(energyRatio * 100).toFixed(1)}%
          </div>
        </div>
      )}
      
      <Canvas
        camera={{ position: [0, 2, 4], fov: 45 }}
        shadows={false} // 禁用阴影以提高性能
        dpr={[1, 1.5]} // 限制最大像素比
      >
        <color attach="background" args={['#000']} />
        <ambientLight intensity={0.5} />
        <directionalLight
          position={[5, 5, 5]}
          intensity={1}
        />
        <pointLight
          position={[-5, -5, -5]}
          intensity={0.5}
          color="#4fc3f7"
        />
        <PlanetWithSuspense energyRatio={energyRatio} />
        <OrbitControls
          enablePan={false}
          minDistance={2}
          maxDistance={10}
          autoRotate={true}
          autoRotateSpeed={0.3} // 降低旋转速度
        />
      </Canvas>
    </div>
  );
};